package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.QueryWrapperUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import com.sk.bilibili.bean.LiveBanner;
import com.sk.bilibili.mapper.LiveBannerMapper;

/**
 * @author 邵康
 * @date 2021/11/26 14:25
 */
@Service
public class LiveBannerService extends ServiceImpl<LiveBannerMapper, LiveBanner> {

    @Autowired
    private MinioService minioService;
    private static final String COVER_PATH = "liveBanner/cover/%s.jpg";
    private static final Pattern COVER_PATTERN = Pattern.compile("/(liveBanner/cover/.*jpg)");

    public R<Void> add(LiveBanner liveBanner) {
        liveBanner.setCover(minioService.add(liveBanner.getCoverFile(), COVER_PATH));
        save(liveBanner);
        return R.success();
    }

    public R<Void> delete(Integer id) {
        LiveBanner temp = getById(id);
        minioService.delete(temp.getCover(), COVER_PATTERN);
        removeById(id);
        return R.success();
    }

    public R<Void> update(LiveBanner liveBanner) {
        LiveBanner temp = getById(liveBanner.getId());
        String cover = minioService.update(COVER_PATH, COVER_PATTERN, temp.getCover(), liveBanner.getCoverFile());
        liveBanner.setCover(cover);
        updateById(liveBanner);
        return R.success();
    }

    public R<IPage<LiveBanner>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page, size), null));
    }

    public R<List<LiveBanner>> getLiveBanner(Integer liveTypeId) {
        QueryWrapper<LiveBanner> queryWrapper = QueryWrapperUtils.eq("live_type_id", liveTypeId);
        return R.success(list(queryWrapper));
    }

}
